/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.ly.wxstore.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.ly.wxstore.comm.Error;
import com.ly.wxstore.entity.goods.GoodsOrder;
import com.ly.wxstore.exception.ApiErrorInfo;
import com.ly.wxstore.exception.ServerException;
import com.ly.wxstore.service.account.ShiroDbRealm.ShiroUser;
import com.ly.wxstore.service.goods.GoodsOrderService;
import com.ly.wxstore.service.goods.GoodsService;
import com.ly.wxstore.service.weixin.WeixinConf;
import com.ly.wxstore.service.weixin.WeixinPayService;
import com.ly.wxstore.vo.ChangeOrderStatusParamsVo;
import com.ly.wxstore.vo.OrderVo;

/**
 * 商城controller
 * 
 * @author peter
 */
@Controller
@RequestMapping(value = "/Order")
public class OrderController {

	private static Logger logger = LoggerFactory.getLogger(OrderController.class);

	@Autowired
	private GoodsOrderService orderService;

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private GoodsOrderService goodsOrderService;

	@Autowired
	private WeixinConf weixinConf;

	@Autowired
	private WeixinPayService weixinPayService;

	/**
	 * 
	 * 我的订单--订单列表
	 * 
	 * @return
	 */
	@RequiresRoles("user")
	@RequestMapping(value = "orderList.json", method = RequestMethod.GET)
	@ResponseBody
	public List<GoodsOrder> orderList() {
		logger.info("orderList");

		List<GoodsOrder> orders = null;
		try {
			orders = orderService.getByOpenid(getCurrentUser().getOpenid());
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return orders;
	}

	/**
	 * 
	 * 修改订单状态
	 * 
	 * @return
	 */
	@RequiresRoles("user")
	@RequestMapping(value = "changeOrderStatus.json", method = RequestMethod.POST)
	@ResponseBody
	public void changeOrderStatus(@RequestBody ChangeOrderStatusParamsVo vo) {
		logger.info("orderList");
		try {
			orderService.changeOrderStatus(getCurrentUser().getOpenid(), vo.getOrderId(), vo.getOrderStatus());
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 准备下订单，创建订单VO，实际数据库中没有创建订单，用户点击支付按钮时才真正在数据库创建订单 支持一个订单多个商品
	 * 
	 * @return
	 */
	@RequiresRoles("user")
	@RequestMapping(value = "preOrderInfo.json", method = RequestMethod.POST)
	@ResponseBody
	public GoodsOrder preOrder(@RequestBody List<OrderVo> OrderVoList) {
		logger.info("preOrder");
		if (OrderVoList == null || OrderVoList.size() == 0) {
			throw new ServerException(Error._50001, Error._50001_MSG);
		}

		GoodsOrder goodsOrder = new GoodsOrder();
		try {
			goodsOrder = goodsOrderService.preOrder(getCurrentUser().getSid(), getCurrentUser().getOpenid(), OrderVoList);
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServerException(Error._10001, Error._10001_MSG);
		}
		return goodsOrder;
	}

	/**
	 * 先创建订单，然后调用支付接口。这样做有两个原因： 1. 订单创建失败: 提交订单，并支付(有支付成功和失败两种状态)。 2. 订单创建成功:
	 * 弹出订单详情页面，并显示订单的状态。
	 * 
	 * @return
	 * @throws ServerException
	 */
	@RequiresRoles("user")
	@RequestMapping(value = "/createOrder", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> createOrder(HttpServletRequest request, @RequestBody GoodsOrder goodsOrder) throws ServerException {
		logger.info("createOrder");

		Map<String, String> params = null;
		try {
			// 创建订单
			goodsOrder.setCreateSid(getCurrentUser().getSid());
			goodsOrder.setOpenid(getCurrentUser().getOpenid());
			goodsOrder.setUpdateSid(getCurrentUser().getSid());
			goodsOrder.setClientIp(request.getRemoteAddr());
			GoodsOrder order = goodsOrderService.createOrder(goodsOrder);

			// 微信支付，调用微信统一下单接口，并返回H5接口所需数据
			params = weixinPayService.publicPay(order, getCurrentUser().getOpenid());
		} catch (ServerException e) {
			logger.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServerException(Error._10001, Error._10001_MSG);
		}

		logger.info("createOrder end/ " + params);
		return params;
	}
	
	public ShiroUser getCurrentUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}

	@ExceptionHandler(ServerException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public ApiErrorInfo handleInvalidRequestError(ServerException ex) {
		return new ApiErrorInfo(ex.getCode(), ex.getMessage());
	}

}
